import re
from collections import defaultdict
import os
import argparse


def process_logs(log_folder_path, output_file_path):
    # 定义正则表达式模式来解析新的日志条目格式
    log_pattern = re.compile(r'(\S+):(\S+):(\d+\.\d+\.\d+\.\d+)->(\d+\.\d+\.\d+\.\d+) send (\d+) Bytes used (\d+) nsec')

    # 定义数据结构来存储结果
    data = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: defaultdict(list))))

    # 遍历日志文件夹下的所有文件并解析
    for log_file in os.listdir(log_folder_path):
        log_file_path = os.path.join(log_folder_path, log_file)
        if os.path.isfile(log_file_path):  # 确保是文件而不是文件夹
            with open(log_file_path, 'r') as file:
                for line in file:
                    match = log_pattern.match(line.strip())
                    if match:
                        node, cards, src_ip, dst_ip, bytes_sent, time_used = match.groups()
                        bytes_sent = int(bytes_sent)
                        time_used = int(time_used)
                        data[node][cards][f"{src_ip}->{dst_ip}"]["bytes_sent"].append(bytes_sent)
                        data[node][cards][f"{src_ip}->{dst_ip}"]["time_used"].append(time_used)

    # 计算每个主机、网卡和数据流方向的传输速率
    results = defaultdict(lambda: defaultdict(list))
    lowest_rate_info = {"node": None, "cards": None, "flow": None, "rate": float('inf')}
    for node, cards_flows in data.items():
        for cards, flows in cards_flows.items():
            for flow, metrics in flows.items():
                total_bytes = sum(metrics["bytes_sent"])
                total_time = sum(metrics["time_used"])
                if total_time > 0:
                    transmission_rate_gbps = (total_bytes * 8) / (total_time * 1e-9) * 1e-9  # 转换比特/秒到Gb/s
                else:
                    transmission_rate_gbps = 0
                results[node][cards].append(transmission_rate_gbps)
                # 比较并找出最低速率
                if transmission_rate_gbps < lowest_rate_info["rate"]:
                    lowest_rate_info = {"node": node, "cards": cards, "flow": flow, "rate": transmission_rate_gbps}

    # 根据网卡进行分组，并计算每组的平均速率
    card_groups = defaultdict(list)
    for node, cards_flows in results.items():
        for cards, rates in cards_flows.items():
            if rates:  # 确保有速率数据
                average_rate = sum(rates) / len(rates)
                card_groups[cards].append((node, cards, average_rate))

    # 计算整个网络的平均传输速率
    total_rates = [rate for node_rates in results.values() for card_rates in node_rates.values() for rate in card_rates]
    if total_rates:
        average_transmission_rate_gbps = sum(total_rates) / len(total_rates)
    else:
        average_transmission_rate_gbps = 0

    # 寻找所有最低速率中最低的那个
    overall_lowest_rate = float('inf')
    overall_lowest_rate_info = None
    for cards, items in card_groups.items():
        for node, cards, rate in items:
            if rate < overall_lowest_rate:
                overall_lowest_rate = rate
                overall_lowest_rate_info = {'node': node, 'cards': cards, 'rate': rate}

    # 输出每个网卡组的平均速率并输出相关信息，包括整个网络中最低的那个速率信息
    with open(output_file_path, 'w') as output_file:
        for cards, items in card_groups.items():
            average_rate = sum(item[2] for item in items) / len(items)
            lowest_rate_info_card = min(items, key=lambda x: x[2])

            output_file.write(f"Cards: {cards}\n")
            output_file.write(f"  Average Transmission Rate:\n")
            output_file.write(
                f"    Average Rate: {average_rate:.9f} Gb/s\n")
            output_file.write(f"  Lowest Transmission Rate:\n")
            output_file.write(
                f"    Node: {lowest_rate_info_card[0]}, Cards: {lowest_rate_info_card[1]}, Transmission Rate: {lowest_rate_info_card[2]:.9f} Gb/s\n")
            output_file.write("\n")

        output_file.write(f"Average Transmission Rate across the Network: {average_transmission_rate_gbps:.9f} Gb/s\n")
        output_file.write(f"Overall Lowest Transmission Rate across the Network:\n")
        output_file.write(
            f"  Node: {overall_lowest_rate_info['node']}, Cards: {overall_lowest_rate_info['cards']}, Transmission Rate: {overall_lowest_rate_info['rate']:.9f} Gb/s\n")

    print(f"Transmission rates by card have been calculated and written to {output_file_path}")
    print(f"Average transmission rate across the network: {average_transmission_rate_gbps:.9f} Gb/s")
    print(f"Overall lowest transmission rate across the network: {overall_lowest_rate_info['rate']:.9f} Gb/s")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Process log files to calculate transmission rates.")
    parser.add_argument("log_folder_path", type=str, help="The path to the log folder.")
    parser.add_argument("output_file_path", type=str, help="The path to the output file.")
    args = parser.parse_args()

    process_logs(args.log_folder_path, args.output_file_path)
